<?php

namespace App\Service\ExternalAPI;

use EchoPHP\Facades\Log;
use EchoPHP\Facades\Request;
use Exception;
use GuzzleHttp\Client;

/**
 * EhireApi接口
 * @package App\Service\ExternalAPI
 */
class EhireApi {

    private $domain = '03';  //RPO系统专用通道：03-RPO

    /**
     * 接口地址
     * @var
     */
    protected $host;

    /**
     * md5加密key
     * @var
     */
    protected $md5key;

    protected $key = '';
    /**
     * 接口超时时间
     * @var
     */
    protected $timeout;

    protected $errorMsg;
    protected $sign = '';


    /**
     * EhireApi constructor.
     * @throws Exception
     */
    public function __construct() {
        //var_dump(encrypt('EhireJava'));
        $options = config('extraapi.ehireapi', []);
        $this->host = $options['host'];
        $this->md5key = $options['md5key'];
        $this->timeout = $options['timeout'];
    }


    /**
     * 登录接口
     * @param $memberName
     * @param $userName
     * @param $passWord
     * @param $allowmultilogin  是否允许用户多点登陆 1.可以 0.不可以
     * @return array|mixed|string
     */
    public function login($memberName, $userName, $passWord, $allowmultilogin = 0) {
        $requestPath = '/innerapi/system/login';
        $getData = [];
        $postData = array(
            'membername' => $memberName,
            'username' => $userName,
            'password' => $passWord,
            'allowmultilogin' => $allowmultilogin
        );
        $content = $this->request($requestPath, 'POST', $getData, $postData);
        return $content;
    }

    /**
     * 退出登录
     * @param $accessKey
     * @return array|mixed|string
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function logout($accessKey) {
        $requestPath = '/innerapi/system/logout';
        $postData = [];
        $getData = array(
            'accesskey' => $accessKey,
        );
        $content = $this->request($requestPath, 'GET', $getData, $postData);
        return $content;
    }

    /**获取用户信息接口
     * @param $accessKey
     * @return array|mixed
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function getUserInfo($accessKey, $hruid) {
        $requestPath = '/innerapi/system/getuserinfo';
        $getData = array(
            'accesskey' => $accessKey,
            'hruid' => $hruid

        );
        $postData = [];
        $content = $this->request($requestPath, 'GET', $getData, $postData);
        return $content;
    }


    /**校验令牌接口
     * @param $accessKey
     * @return array|mixed
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function checkAccessKey($accessKey) {
        $requestPath = '/innerapi/system/checkaccesskey';
        $getData = array(
            'accesskey' => $accessKey
        );
        $postData = [];
        $content = $this->request($requestPath, 'GET', $getData, $postData);
        return $content;
    }

    /**
     * 新增用户
     * @param $accessKey
     * @param $userName
     * @param $name
     * @param $email
     * @return array|mixed|string
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function addUser($accessKey, $userName, $name, $email) {
        $requestPath = '/innerapi/system/adduser';
        $postData = array(
            'accesskey' => $accessKey,
            'username' => $userName,
            'name' => $name,
            'email' => $email
        );
        $getData = [];
        $content = $this->request($requestPath, 'POST', $getData, $postData);
        return $content;
    }

    /**
     * 添加已有用户
     * @param $accessKey
     * @param $hrUid
     * @return array|mixed|string
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function addExistUser($accessKey, $hrUid) {
        $requestPath = '/innerapi/system/addexistUser';
        $postData = array(
            'accesskey' => $accessKey,
            'hruid' => $hrUid,
        );
        $getData = [];
        $content = $this->request($requestPath, 'POST', $getData, $postData);
        return $content;
    }

    /**
     * 修改用户信息
     * @param $accessKey
     * @param $email
     * @param $hrUid
     * @param $userName
     * @param $name
     * @return array|mixed|string
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function updateUserInfo($accessKey, $email, $hrUid, $userName, $name) {
        $requestPath = '/innerapi/system/updateuserinfo';
        $postData = array(
            'accesskey' => $accessKey,
            'email' => $email,
            'hruid' => $hrUid,
            'username' => $userName,
            'name' => $name
        );
        $getData = [];
        $content = $this->request($requestPath, 'POST', $getData, $postData);
        return $content;
    }

    /**删除用户接口
     * @param $accessKey
     * @param $hruids
     * @return array|mixed
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function deleteUsers($accessKey, $hruids) {
        $requestPath = '/innerapi/system/deleteusers';
        $getData = [];
        $postData = array(
            'accesskey' => $accessKey,
            'hruids' => $hruids
        );
        $content = $this->request($requestPath, 'POST', $getData, $postData);
        return $content;
    }

    /**
     * 获取用户列表
     * @param $accessKey
     * @param $pageIndex
     * @param $pageSize
     * @param $sort
     * @param $where
     * @return array|mixed|string
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function getUserList($accessKey, $pageIndex, $pageSize, $sort, $where) {
        $requestPath = '/innerapi/system/getuserlist';
        $getData = [];
        $postData = array(
            'accesskey' => $accessKey,
            'pageindex' => $pageIndex,
            'pagesize' => $pageSize,
            'sort' => $sort,
            'where' => $where
        );
        $content = $this->request($requestPath, 'POST', $getData, $postData);
        return $content;
    }

    /**
     * 获取用户列表（无需登录，给精英组使用）
     * @param $accessKey
     * @param $pageIndex
     * @param $pageSize
     * @param $sort
     * @param $where
     * @return array|mixed|string
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function getUserList2($ctmid, $pageIndex, $pageSize, $sort, $where) {
        $requestPath = '/innerapi/system/getuserlist2';
        $getData = [];
        $postData = array(
            'ctmid' => $ctmid,
            'pageindex' => $pageIndex,
            'pagesize' => $pageSize,
            'sort' => $sort,
            'where' => $where
        );
        $content = $this->request($requestPath, 'POST', $getData, $postData);
        return $content;
    }

    /**
     * 重新发送邮件
     * @param $accessKey
     * @param $hrUid
     * @return array|mixed|string
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function resendNewUserVerifyEmail($accessKey, $hrUid) {
        $requestPath = '/innerapi/system/resendnewuserverifyemail';
        $getData = [];
        $postData = array(
            'accesskey' => $accessKey,
            'hruid' => $hrUid,
        );
        $content = $this->request($requestPath, 'POST', $getData, $postData);
        return $content;
    }

    /**
     * Notes:crmaccsubid下ctm列表及用户
     * @param $crmAccSubId
     * @return array|mixed|string
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function getUserListByAccsubid($crmAccSubId) {
        $requestPath = '/innerapi/system/getuserlistbyaccsubid';
        $getData = [];
        $postData = array(
            'crmaccsubid' => $crmAccSubId,
            'domain' => $this->domain,
        );
        $content = $this->request($requestPath, 'POST', $getData, $postData);
        return $content;
    }

    /**
     * 账号管理URL
     * @param $accessKey
     * @return array|mixed|string
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function ehireManageUrl($accessKey) {
        $options = config('extraapi.ehiremanage', []);
        $urlStr = $options['host'];
        $urlStr = str_replace('{domain}', $this->domain, $urlStr);
        $urlStr = str_replace('{accesskey}', $accessKey, $urlStr);

        $urlArr = ['emailUrl' => $urlStr, 'mobileUrl' => $urlStr, 'passwordUrl' => $urlStr,];
        return ["code" => "000000", "msg" => "", "data" => $urlArr];
    }

    /**
     * 网才找回密码URL
     * @param $accessKey
     * @return array|mixed|string
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function ehireFindPasswordUrl() {
        $options = config('extraapi.ehiremanage', []);
        $urlStr = str_replace('{domain}', $this->domain, $options['FindPasswordByEmail']);
        $urlArr = ['passwordUrl' => $urlStr];
        return ["code" => "000000", "msg" => "", "data" => $urlArr];
    }

    /**接口访问业务控制
     * @param $requestPath
     * @param $callType : POST 或者 GET
     * @param $getData
     * @param $postData
     * @return array|mixed|string
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    private function request($requestPath, $callType, $getData, $postData) {
        if (!in_array($callType, array('POST', 'GET'))) {
            return ["code" => "99999", "msg" => "现在系统忙，请稍候再试！", "data" => '01'];
        }

        //键名转小写
        $getData = array_change_key_case($getData, CASE_LOWER);
        $postData = array_change_key_case($postData, CASE_LOWER);

        $clientIp = Request::instance()->getClientIp();
        $clientPort = Request::instance()->getClientPort();

        //数据urlencode编码
        $getData_urlencode = [];
        $encodeKeyName = ['membername', 'username', 'name', 'email', 'password'];  //where
        foreach ($getData as $key => $item) {
            if (in_array($key, $encodeKeyName)) {
                $item = urlencode($item);
            }
            $getData_urlencode[$key] = $item;
        }

        $postData_urlencode = [];
        foreach ($postData as $key => $item) {
            if (in_array($key, $encodeKeyName)) {
                $item = urlencode($item);
            }
            $postData_urlencode[$key] = $item;
        }

        //参数加密KEY
        if ($callType == 'GET') {
            $getData_urlencode['domain'] = $this->domain;
            $getData_urlencode['clientip'] = $clientIp;
            $getData_urlencode['clientport'] = $clientPort;
            foreach ($postData_urlencode as $key => $item) {
                if (isset($getData_urlencode[$key])) {
                    unset($postData_urlencode[$key]);
                }
            }
        } else {
            $postData_urlencode['domain'] = $this->domain;
            $postData_urlencode['clientip'] = $clientIp;
            $postData_urlencode['clientport'] = $clientPort;
            foreach ($getData_urlencode as $key => $item) {
                if (isset($postData_urlencode[$key])) {
                    unset($getData_urlencode[$key]);
                }
            }
        }

        //GET方式URL拼接
        $query = http_build_query($getData_urlencode);
        if (!empty($query)) {
            $query .= '&';
        }
        $query .= time();
        $requestUrl = $requestPath . '?' . $query;

        //参数聚合
        $allData = $getData_urlencode;
        foreach ($postData_urlencode as $key => $item) {
            $allData[$key] = $item;
        }

        //参数键名正序排序
        ksort($allData);

        //按参数名升序排列的参数值字符串连接
        $allValue = '';
        foreach ($allData as $key => $item) {
            $allValue .= $item;
        }

        //生成参数校验码 md5(md5(参数值字符串连接（不包括key本身）+’EhireJava’))
        $this->key = md5(md5($allValue . $this->md5key));

        //传入参数key
        if ($callType == 'GET') {
            $requestUrl .= '&key=' . $this->key;
        } else {
            $postData_urlencode['key'] = $this->key;
        }

        //调试工具
        if (1 == 0 && $requestPath == '/innerapi/system/login') {
            var_dump($callType);
            var_dump($requestUrl);
            var_dump($getData_urlencode);
            var_dump($postData_urlencode);
            var_dump($allData);
        }

        $client = new Client([
            'base_uri' => $this->host,
            'timeout' => $this->timeout
        ]);

        $content = [];
        try {
            $response = $client->request($callType, $requestUrl, ['form_params' => $postData_urlencode]);
            $content = $response->getBody()->getContents();
            $content = json_decode($content, true);
            if (!isset($content['code'])) {
                $content = ["code" => "99999", "msg" => "现在系统忙，请稍候再试！", "data" => '02'];
            }
        } catch (Exception $e) {
            $this->errorMsg = $e->getMessage();
            Log::error($this->errorMsg, [
                'requestUrl' => $requestUrl,
                'callType' => $callType,
                'getdata' => $getData,
                'postdata' => $postData
            ]);
            $content = ["code" => "99999", "msg" => "现在系统忙，请稍候再试！", "data" => '03'];
        }
        return $content;
    }


    /**测试 不需要送测
     * @param $requestPath
     * @param $callType : POST 或者 GET
     * @param $getData
     * @param $postData
     * @return array|mixed|string
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function requestTest($requestPath, $callType, $getData, $postData) {
        //键名转小写
        $getData = array_change_key_case($getData, CASE_LOWER);
        $postData = array_change_key_case($postData, CASE_LOWER);

        //数据urlencode编码
        $getData_urlencode = [];
        $encodeKeyName = ['membername', 'username', 'name', 'email', 'password'];  //where
        foreach ($getData as $key => $item) {
            if (in_array($key, $encodeKeyName)) {
                $item = urlencode($item);
            }
            $getData_urlencode[$key] = $item;
        }

        $postData_urlencode = [];
        foreach ($postData as $key => $item) {
            if (in_array($key, $encodeKeyName)) {
                $item = urlencode($item);
            }
            $postData_urlencode[$key] = $item;
        }

        //参数加密KEY
        if ($callType == 'GET') {
            foreach ($postData_urlencode as $key => $item) {
                if (isset($getData_urlencode[$key])) {
                    unset($postData_urlencode[$key]);
                }
            }
        } else {
            foreach ($getData_urlencode as $key => $item) {
                if (isset($postData_urlencode[$key])) {
                    unset($getData_urlencode[$key]);
                }
            }
        }

        //GET方式URL拼接
        $query = http_build_query($getData_urlencode);
        $requestUrl = $requestPath . '?' . $query;

        //参数聚合
        $allData = $getData_urlencode;
        foreach ($postData_urlencode as $key => $item) {
            $allData[$key] = $item;
        }

        //参数键名正序排序
        ksort($allData);

        //按参数名升序排列的参数值字符串连接
        $allValue = '';
        foreach ($allData as $key => $item) {
            $allValue .= $item;
        }

        //生成参数校验码 md5(md5(参数值字符串连接（不包括key本身）+’EhireJava’))
        $this->key = md5(md5($allValue . $this->md5key));

        //传入参数key
        if ($callType == 'GET') {
            $requestUrl .= '&key=' . $this->key;
        } else {
            $postData_urlencode['key'] = $this->key;
        }
        var_dump($postData_urlencode);
    }
}